﻿using _11Net8AspNetCore_WebApis.Model;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace _11Net8AspNetCore_WebApis.BandModel
{
    /// <summary>
    /// 模型绑定
    /// </summary>
    public class CookieBangModel : IModelBinder
    {
        /// <summary>
        /// Cookie绑定到用户模型
        /// </summary>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        Task IModelBinder.BindModelAsync(ModelBindingContext bindingContext)
        {
            // 1、获取用户模型
            Type type = bindingContext.ModelType;
            // 1.2 获取Cookie
            var cookies = bindingContext.HttpContext.Request.Cookies;

            //2\判断是否为用户模型
            if (type == (typeof(UserModel)))
            {
                // 3、开始绑定
                // 3.1 赋值
                UserModel user = new UserModel();
                user.Id = int.Parse(cookies["Id"]);
                user.Name = cookies["Name"];

                //3.2 开始绑定
                bindingContext.Result = ModelBindingResult.Success(user);
            }

            return Task.CompletedTask;
        }
    }
}
